package com.cloud.hotline.common.exception;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cloud.hotline.common.result.Quokka;

@ControllerAdvice
public class QkGlobalExceptioinHander {
	private static final Logger logger = LoggerFactory.getLogger(QkGlobalExceptioinHander.class);
	private static final String ERROR_MSG = "系统错误";
	private static final String APPLICATION_JSON = "application/json";

	@ExceptionHandler(value = Exception.class)
	@ResponseBody
	public Quokka resolveException(HttpServletRequest request, HttpServletResponse resp, Object obj, Exception e) {
		if (e instanceof java.net.SocketException) {
			return null;
		}
		resp.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
		// 记录请求参数到错误日志中
		StringBuffer paramBuffer = new StringBuffer();
		paramBuffer.append("请求参数: \n");
		if (request.getHeader("Content-Type").indexOf(APPLICATION_JSON) >= 0) {
			// 采用读流的当时，从请求中获取参数
		} else {
			Enumeration<String> enu = request.getParameterNames();
			if (enu != null) {
				while (enu.hasMoreElements()) {
					String paramName = enu.nextElement();
					if ("_".equals(paramName))
						continue;
					paramBuffer.append(paramName + ":" + request.getParameter(paramName) + ";");
				}
			}
		}
		logger.error(paramBuffer.toString(), e);

		// 封装异常信息
		Quokka result = new Quokka(false);
		if (logger.isDebugEnabled()) {
			StringBuffer errorStack = new StringBuffer(paramBuffer.toString());
			StackTraceElement[] eles = e.getStackTrace();
			for (StackTraceElement ele : eles) {
				errorStack.append(ele.toString()).append("\r\n");
			}
			result.getDataMap().put("msg", errorStack);
		}
		if (e instanceof BizException) {
			result.setMessage(e.getMessage());
		} else {
			result.setMessage(ERROR_MSG);
		}

		return result;
	}

}
